package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.process.storage.model.CsfAssurance;
import com.sangmo.fts.process.storage.model.CsfContract;
import com.sangmo.fts.process.storage.model.CsfLoan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class CsfAssuranceService extends DelegateViewService<CsfAssurance> {

    @Autowired
    private CsfAssuranceEntityService csfAssuranceEntityService;

    @Autowired
    private CsfLoanService csfLoanService;

    @Autowired
    private CsfContractService csfContractService;

    @Override
    protected ViewService<CsfAssurance> getEntityService() {
        return csfAssuranceEntityService;
    }

    public void buyerConfirm(Long id) {
        CsfAssurance assurance = this.get(id);
        if (assurance.isBuyerConfirm()) {
            throw new ServiceException(StandardErrors.EXTERNAL_ERROR.getStatus(), "error.csfAssurance.buyerConfirm.permit.disabled");
        }
        csfAssuranceEntityService.buyerConfirm(assurance);
        afterConfirm(assurance);
    }

    private void afterConfirm(CsfAssurance assurance) {
        CsfLoan loan = csfLoanService.get(assurance.getLoanId());
        loan.setAssuranceId(assurance.getId());
        csfLoanService.save(loan);
    }

    public PageResult listItemsByPage(Long id, PageSearch ps) {
        CsfAssurance assurance = this.get(id);
        CsfLoan loan = csfLoanService.get(assurance.getLoanId());
        return csfContractService.listItemsByPage(loan.getContractId(), ps);
    }


}
